import traceback
from django.contrib import admin
from app.models import PatientProfile, Title, UserProfile, EmployeeProfile, PatientAppointment, Prescription, Medication, Diagnosis
from django.contrib.auth.models import Group
from django.contrib.sites.models import Site
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User, Permission, ContentType


# define the UserProfile
class UserProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = True
    verbose_name = 'Base Profile'
    max_num = 1

class EmployeeProfileInline(admin.TabularInline):
    model = EmployeeProfile
    can_delete = True
    verbose_name = 'Employee Profile'
    max_num = 1
        
class PatientAppointmentInline(admin.TabularInline):
    model = PatientAppointment
    can_delete = True;
    verbose_name = "Appointment"
    max_num = 100
    extra = 0
    
class PrescriptionInline(admin.TabularInline):
    model = Prescription
    can_delete = True;
    verbose_name = "Prescription"
    max_num = 100
    extra = 0

class DiagnosisInline(admin.TabularInline):
    model = Diagnosis
    can_delete = True;
    verbose_name = "Diagnosis"
    max_num = 1
    extra = 0
    
class PatientAppointmentAdmin(admin.ModelAdmin):
    inlines = (PatientAppointmentInline,)

class EmployeeProfileAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        if obj:
            return ['user']
        else:
            return []

class PatientProfileAdmin(admin.ModelAdmin):
    inlines = (PatientAppointmentInline,PrescriptionInline,DiagnosisInline)
    def get_readonly_fields(self, request, obj=None):
        if obj:
            return ['user']
        else:
            return []

class BasicUserAdmin(UserAdmin):
    inlines = (UserProfileInline,)
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        #(('Personal Information'), {'fields': ('first_name', 'last_name', 'email')}),
        (('Roles'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups')}),
        (('Important dates'), {'fields': ('last_login', 'date_joined')})
        )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'password1', 'password2', 'first_name', 'last_name', 'email')}
        ),
    )
    def queryset(self,request):
        qs = admin.ModelAdmin.queryset(self,request)
        if request.user.is_superuser:
            return qs
        # Only allow viewing/editing users who are not superusers
        return qs.filter(is_superuser=False)
    def get_readonly_fields(self, request, obj=None):
        # Deny editing groups, permissions and the superuser status
        return () if request.user.is_superuser else ('is_superuser', 'groups', 'user_permissions', 'last_login', 'date_joined', )



def userExists(username):
    if User.objects.filter(username=username).count():
        return True
    return False

admin.site.unregister(User)
admin.site.unregister(Site)
admin.site.unregister(Group)
admin.site.register(Permission)
admin.site.register(Medication)
admin.site.register(PatientProfile, PatientProfileAdmin)
admin.site.register(EmployeeProfile, EmployeeProfileAdmin)
admin.site.register(User, BasicUserAdmin)

admin.site.register(Group)
admin.site.register(Title)


try:
    # Single row representing the Role, Object to which permissions apply, and the types of permissions
    acl_role_row = ('Doctor','medication', ('add_medication','change_medication', 'delete_medication'))
    current_role, current_role_created = Group.objects.get_or_create(name=acl_role_row[0])
    content = ContentType.objects.get(model=acl_role_row[1])
    for i in range(len(acl_role_row[2])):
        current_role.permissions.add(Permission.objects.get(content_type=content, codename=acl_role_row[2][i]))
    
    # Single row representing the username and the Role that should be assigned
    acl_user_role_row = ('adoctor', 'Doctor')
    
    # Assign the role to the user if both user and role exist 
    if User.objects.filter(username=acl_user_role_row[0]).count() and Group.objects.filter(name=acl_user_role_row[1]).count():
        current_role = Group.objects.get(name=acl_user_role_row[1])
        user = User.objects.get(username=acl_user_role_row[0])
        current_role.user_set.add(user);
except:
    traceback.print_stack()
    
    
    